<template>
<div class="crypto">
  <h1>Testing Text Crypto <small>(text encryption then decryption)</small></h1>
  <div v-if="rsaPvtKey">
    <form @submit.prevent="encryptText(text, rsaPvtKey);">
      <input type="text" v-model="text" />
      <button>Submit</button>
      <button type="button"
              aria-label="Clear"
              v-show="text || encr || decr"
              v-on:click="clear()">
        X</button>
    </form>
    <pre v-show="text">{{text}}</pre>
    <pre v-show="encr">{{encr}}</pre>
    <pre v-show="decr">{{decr}}</pre>
    <pre v-if="done && !matchesVal">
      {{done}}
      {{matchesVal}}
      {{matchesTyp}}
      {{textType}}
      {{decrType}}
      {{decr.length}}
      {{text.length}}
    </pre>
  </div>
  <div v-else>
    <p>no private key</p>
  </div>
</div>
</template>

<script>
export default {
    name: "TextCrypto",
    props: [
        "rsaPvtKey"
    ],
    data() {
        return {
            done: true,
            text: "",
            encr: "",
            decr: ""
        }
    },
    computed: {
        matchesVal() { return this.text === this.decr },
        matchesTyp() { return this.textType === this.decrType },
        textType() { return typeof this.text },
        decrType() { return typeof this.decr },
    },
    methods: {
        clear: function() {
            this.text = ""
            this.encr = ""
            this.decr = ""
        },
        encryptText: function(toEncrypt, privatekey) {
            this.encr = ""
            this.decr = ""

            const crypto = require("crypto");
            const constants = require("constants");
            const bufferToEncrypt = new Buffer(toEncrypt);
            const padding = constants.RSA_PKCS1_PADDING;
            const encrypted = crypto.publicEncrypt(
                {
                    key: privatekey,
                    padding: padding,
                },
                bufferToEncrypt);
            
            this.encr = encrypted.toString("base64");
            
            this.decr = crypto.privateDecrypt(
                {
                    key: privatekey,
                    padding: padding,
                },
                new Buffer(this.encr, "base64"))
                .toString();
        },
    },
    watch: {
        decr() { this.done = true },
        text() { this.done = false },
    },
}
</script>

<style scoped>
.crypto {
    background: #ffccaa;
}
pre {
    background: #550000;
    color: #00ff77;
}
</style>
